/**
 * 查询用户信息
 */
import React, { Component } from 'react';
import { message, Input, Button } from 'antd';
// import XLSX from 'xlsx';
import { api } from '../../constants';
import { fetch, funDownload } from '../../utils';
import './style.scss';

function Info({ data = {} }) {
  if (data.id) {
    const { id, flower, godLevel, guildName, speaker, reduceFlower } = data;
    return (
      <div>
        id: {id}，公会：{guildName}，鲜花：{flower}，喇叭：{speaker}，贡献：{reduceFlower}，花神等级：{godLevel}
      </div>
    );
  }
  return <div />;
}

export default class Index extends Component {
  state = {
    userList1: [],
    userList: [],
    firstValue: '',
    lastValue: '',
  }
  // 获取用户信息
  async getUserInfo(id) {
    if (!id) {
      message.error('请输入id');
      return;
    }
    const params = {
      openId: window.btoa(window.btoa(`${id}yqcmxssLcJL1l8jnlC`)),
    };
    const response = await fetch(`${api.userInfo}`, {
      method: 'POST',
      body: params,
    });
    if (response.msgCode === 'S0000') {
      return response.data.user || {};
    }
    message.error(`查询失败 ${response.message}`);
  }

  queryUserInfo = (value) => {
    if (!value) {
      message.error('请输入要祝福好友的ID');
    }

    const valueList = value.replace(/\s/g, '').replace(/(,|，)/g, ',').split(',');
    this.setState({ userList1: [] });
    valueList.forEach((v, i) => {
      setTimeout(() => {
        this.getUserInfo(v).then((userinfo) => {
          if (userinfo) {
            this.setState(state => ({ userList1: [...state.userList1, userinfo] }));
          }
        });
      }, 1500 * i);
    });
  }

  batchQuery = () => {
    const { firstValue, lastValue } = this.state;
    if (!firstValue) {
      message.error('请输入第一个要查的id');
      return;
    }
    this.setState({ userList: [] });
    for (let i = Number(firstValue); i <= Number(lastValue); i += 1) {
      setTimeout(() => {
        this.getUserInfo(i).then((userinfo) => {
          if (userinfo) {
            this.setState(state => ({ userList: [...state.userList, userinfo] }));
          }
        });
      }, 1500 * (i - firstValue));
    }
  }

  batchQueryAndSave = () => {
    const { firstValue, lastValue } = this.state;
    if (!firstValue) {
      message.error('请输入第一个要查的id');
      return;
    }
    this.setState({ userList: [] });
    for (let i = Number(firstValue); i <= Number(lastValue); i += 1) {
      setTimeout(() => {
        this.getUserInfo(i).then((userinfo) => {
          if (userinfo) {
            this.setState(state => {
              // 最后一个存数据
              if (i === Number(lastValue)) {
                try {
                  const userListString = sessionStorage.getItem('userList') || '[]';
                  const userList = JSON.parse(userListString).map(({ id, flower, godLevel, guildName }) => ({ id, guildName, flower, godLevel }));
                  const string = this.convertToSheet(userList);
                  funDownload(string, `${firstValue}-${lastValue}数据.txt`);
                } catch (err) { message.error('下载出错了~'); console.log(err); }
              } else {
                sessionStorage.setItem('userList', JSON.stringify(state.userList));
              }
              return { userList: [...state.userList, userinfo] };
            });
          }
        });
      }, 1500 * (i - firstValue));
    }
  }

  convertToSheet = (userList) => {
    const data = [];
    data.push(['id', '公会', '鲜花', '等级']);
    userList.forEach(({ id, flower, godLevel, guildName }) => {
      data.push([id, guildName, flower, godLevel]);
    });
    // console.log('userList: ', data);
    const excelData = data.map((childArr) => (childArr.join(' '))).join('\n');
    // console.log('excelData: ', excelData);
    return excelData;
  }

  render() {
    const { userList1, firstValue, lastValue, userList } = this.state;
    return (
      <div className="index">
        <p />
        <p />
        <p>
          查询用户信息：
          <Input.Search
            className="bless-search"
            placeholder="输入要查询的ID,多个可用，隔开"
            enterButton="查询"
            onSearch={this.queryUserInfo.bind(this)}
          />
        </p>
        {
          userList1.length ?
            userList1.map(user => <p><Info data={user} /></p>) :
            null
        }
        <p />
        <p />
        <p />
        <p />
        <h3>批量查询</h3>
        <p className="query-userinfo-batch">
          <Input className="query-userinfo-input" value={firstValue} type="number" onChange={(e) => { this.setState({ firstValue: e.target.value }); }} placeholder="请输入第一个要查的id" />
          &nbsp;~&nbsp;<Input className="query-userinfo-input" value={lastValue} type="number" onChange={(e) => { this.setState({ lastValue: e.target.value }); }} placeholder="请输入最后一个要查的id" />
          &nbsp;&nbsp;&nbsp;&nbsp;<Button onClick={this.batchQuery} type="primary">批量查询</Button>
          &nbsp;&nbsp;&nbsp;&nbsp;<Button onClick={this.batchQueryAndSave} type="primary">批量查询并保存</Button>
        </p>
        {
          userList.length ?
            userList.map(user => <p><Info data={user} /></p>) :
            null
        }
      </div>
    );
  }
}
